import React, { PureComponent } from 'react';
import { FormattedMessage, setLocale, getLocale } from 'umi/locale';
import { Spin, Tag, Menu, Icon, Dropdown, Avatar, Tooltip, Button } from 'antd';
import moment from 'moment';
import groupBy from 'lodash/groupBy';
import NoticeIcon from '../NoticeIcon';
import HeaderSearch from '../HeaderSearch';
import styles from './index.less';

export default class GlobalHeaderRight extends PureComponent {
  getNoticeData() {
    const { notices = [] } = this.props;
    
    if (notices.length === 0) {
      return {};
    }
    
    const newNotices = notices.map(notice => {
      const newNotice = { ...notice };
      if (newNotice.datetime) {
        newNotice.datetime = moment(notice.datetime).fromNow();
      }
      if (newNotice.id) {
        newNotice.key = newNotice.id;
      }
      if (newNotice.extra && newNotice.status) {
        const color = {
          todo: '',
          processing: 'blue',
          urgent: 'red',
          doing: 'gold',
        }[newNotice.status];
        newNotice.extra = (
          <Tag color={color} style={{ marginRight: 0 }}>
            {newNotice.extra}
          </Tag>
        );
      }
      return newNotice;
    });
    //console.log(newNotices);
    return groupBy(newNotices, 'type');
  }

  changLang = () => {
    const locale = getLocale();
    if (!locale || locale === 'zh-CN') {
      setLocale('en-US');
    } else {
      setLocale('zh-CN');
    }
  };

  render() {
    const {
      currentUser,
      fetchingNotices,
      onNoticeVisibleChange,
      onMenuClick,
      onNoticeClear,
      theme,
      
    } = this.props;
    const { dispatch } = this.props;

    const dwlist =JSON.parse(localStorage.getItem("DWList")) ;
    
    if(dwlist){
       var children= [];
       for (let i = 0; i < dwlist.length; i++) {
        children.push(<Menu.Item key={dwlist[i]['Admin_DW_id']}><Icon type="setting" /> {dwlist[i]['Admin_DW_name']}</Menu.Item>);
      }
      console.log(children);
      var menus = (
        <Menu className={styles.menu} selectedKeys={[]} onClick={onMenuClick}>
          <Menu.Item key="userCenter">
            <Icon type="user" />
            <FormattedMessage id="menu.account.center" defaultMessage="account center" />
          </Menu.Item>
          <Menu.Item key="userinfo">
            <Icon type="setting" />
            <FormattedMessage id="menu.account.settings" defaultMessage="account settings" />
          </Menu.Item>
          <Menu.SubMenu title="切换组织" key="qhzz" >
          
          {children}
          </Menu.SubMenu>
          {/* <Menu.Item key="triggerError">
            <Icon type="close-circle" />
            <FormattedMessage id="menu.account.trigger" defaultMessage="Trigger Error" />
          </Menu.Item> */}
          <Menu.Item key="clearall">
            <Icon type="setting" />
            清除所有缓存
          </Menu.Item>
          <Menu.Divider />
          <Menu.Item key="logout">
            <Icon type="logout" />
            退出登录
          </Menu.Item>
        </Menu>
      );
    }else{
      dispatch({
        type: 'login/logout',
      });
      return false;
    }
    const menu = (
      <Menu className={styles.menu} selectedKeys={[]} onClick={onMenuClick}>
        <Menu.Item key="userCenter">
          <Icon type="user" />
          <FormattedMessage id="menu.account.center" defaultMessage="account center" />
        </Menu.Item>
        <Menu.Item key="userinfo">
          <Icon type="setting" />
          <FormattedMessage id="menu.account.settings" defaultMessage="account settings" />
        </Menu.Item>
       
        {/* <Menu.Item key="triggerError">
          <Icon type="close-circle" />
          <FormattedMessage id="menu.account.trigger" defaultMessage="Trigger Error" />
        </Menu.Item> */}
        <Menu.Item key="clearall">
            <Icon type="setting" />
            清除所有缓存
          </Menu.Item>
        <Menu.Divider />
        <Menu.Item key="logout">
          <Icon type="logout" />
          退出登录
        </Menu.Item>
      </Menu>
    );
   
    const noticeData = this.getNoticeData();
    let className = styles.right;
    if (theme === 'dark') {
      className = `${styles.right}  ${styles.dark}`;
    }
    //console.log(noticeData)
    return (
      <div className={className}>
        {/* <HeaderSearch
          className={`${styles.action} ${styles.search}`}
          placeholder="站内搜索"
          dataSource={['搜索提示一', '搜索提示二', '搜索提示三']}
          onSearch={value => {
            console.log('input', value); // eslint-disable-line
          }}
          onPressEnter={value => {
            console.log('enter', value); // eslint-disable-line
          }}
        /> */}
        <Tooltip title="使用文档">
          <a
            target="_blank"
            href="https://timkj.com"
            rel="noopener noreferrer"
            className={styles.action}
            title="使用文档"
          >
            <Icon type="question-circle-o" />
          </a>
        </Tooltip>
        <NoticeIcon
          className={styles.action}
          count={currentUser.notifyCount}
          onItemClick={(item, tabProps) => {
            console.log(item.id); // eslint-disable-line
            dispatch({
              type:'ModeMsg/setcheckupmsg',
              payload:{
                msg_id:item.id
              }
            })
            dispatch({
              type:"global/fetchNotices"
            })
          }}
          onClear={onNoticeClear}
          onPopupVisibleChange={onNoticeVisibleChange}
          loading={fetchingNotices}
          popupAlign={{ offset: [20, -16] }}
          locale={{ emptyText: '暂无数据', clear: '清空' }}
        >
          <NoticeIcon.Tab
            list={noticeData['notification']}
            title="通知"
            emptyText="你已查看所有通知"
            emptyImage="https://gw.alipayobjects.com/zos/rmsportal/wAhyIChODzsoKIOBHcBk.svg"
            showClear={false}
          />
          <NoticeIcon.Tab
            list={noticeData['message']}
            title="消息"
            emptyText="您已读完所有消息"
            emptyImage="https://gw.alipayobjects.com/zos/rmsportal/sAuJeJzSKbUmHfBQRzmZ.svg"
            showClear={false}
          />
          <NoticeIcon.Tab
            list={noticeData['event']}
            title="待办"
            emptyText="你已完成所有待办"
            emptyImage="https://gw.alipayobjects.com/zos/rmsportal/HsIsxMZiWKrNUavQUXqx.svg"
            showClear={false}
          />
        </NoticeIcon>
        {currentUser.name ? (
          <Dropdown overlay={(menus)?menus:menu}>
            <span className={`${styles.action} ${styles.account}`}>
              <Avatar
                size="small"
                className={styles.avatar}
                src={currentUser.avatar}
                alt="avatar"
              />
              <span className={styles.name}>{currentUser.name}</span>
            </span>
          </Dropdown>
        ) : (
          <Spin size="small" style={{ marginLeft: 8, marginRight: 8 }} />
        )}
        {/* <Button
          size="small"
          ghost={theme === 'dark'}
          style={{
            margin: '0 8px',
          }}
          onClick={() => {
            this.changLang();
          }}
        >
        
        
          <FormattedMessage id="navbar.lang" />
        </Button> */}
        <Button 
        size = 'small'
        ghost={theme === 'dark'}
        style={{
          margin: '0 8px',
        }}
        onClick={() => {
          sessionStorage.clear();
          this.forceUpdate();
        }}
        >
        <Icon type="redo" />
        </Button>
        
      </div>
    );
  }
}
